package com.yxd.demo.controller;

import cn.hutool.json.JSONUtil;
import com.yxd.demo.domain.*;
import com.yxd.demo.dto.CouponDto;
import com.yxd.demo.service.CouponService;
import com.yxd.demo.service.MarketingWayService;
import com.yxd.demo.service.RuleService;
import com.yxd.demo.util.RuleUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.api.Facts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author: yxd
 * @date: 2022/8/1 9:39
 */
@RestController
@Slf4j
@RequestMapping(value = "/rule")
public class RuleController {
    @Autowired
    private RuleService ruleService;
    @Autowired
    private RuleUtil ruleUtil;
    @Autowired
    private CouponService couponService;

    @PostMapping(value = "/addRule")
    public Result addRule(@RequestBody Rule rule) {
        return ruleService.insert(rule) ? Result.ok("", null) : Result.fail("", null);
    }

    @PostMapping(value = "/enableRule")
    public Store enableRule(@RequestBody Store store) {
        Facts facts = new Facts();
        facts.put("store", store);
        facts.put("marketingWayService", MarketingWayService.class);
        List<Rule> ruleList = ruleService.queryAll();
        ruleUtil.fireRule(ruleList, facts);
        return facts.get("store");
    }

    @PostMapping(value = "/discount")
    public CouponDto discount(@RequestBody Product product) {
        List<Coupon> couponList = couponService.queryCouponList("123456789");
        if (CollectionUtils.isEmpty(couponList)) {
            return CouponDto.builder().build();
        }
        Facts facts = new Facts();
        facts.put("product", product);
        facts.put("couponList", couponList);
        ruleUtil.fireRuleWithAnnotation(facts);
        CouponDto couponDto = facts.get("couponDto");
        return Objects.isNull(couponDto) ? CouponDto.builder().build() : couponDto;
    }
}
